package com.ssy.lingxi.marketing.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.marketing.BelongTypeEnum;
import com.ssy.lingxi.common.constant.product.PriceTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.marketing.constant.MarketingFieldsEnum;
import com.ssy.lingxi.marketing.entity.activity.*;
import com.ssy.lingxi.marketing.model.bo.*;
import com.ssy.lingxi.marketing.model.constant.ActivityGoodsAuditStatusEnum;
import com.ssy.lingxi.marketing.model.constant.FullQuantityTypeEnum;
import com.ssy.lingxi.marketing.model.constant.MerchantActivityInnerStatusEnum;
import com.ssy.lingxi.marketing.model.constant.PlatformActivityOuterStatusEnum;
import com.ssy.lingxi.marketing.model.vo.activity.request.*;
import com.ssy.lingxi.marketing.model.vo.activity.response.*;
import com.ssy.lingxi.marketing.repository.*;
import com.ssy.lingxi.marketing.service.IActivityOrderService;
import com.ssy.lingxi.marketing.service.IAdornService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BaseActivityService;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityGoodsHandleComponent;
import com.ssy.lingxi.search.api.feign.ISearchFeign;
import com.ssy.lingxi.search.api.feign.ITemplateChannelFeign;
import com.ssy.lingxi.search.api.feign.ITemplateFeign;
import com.ssy.lingxi.search.api.model.request.CommoditySkuRequest;
import com.ssy.lingxi.search.api.model.request.TemplateCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.request.channel.TemplateChannelCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.CommoditySearchResponse;
import com.ssy.lingxi.search.api.model.response.CommoditySkuResponse;
import com.ssy.lingxi.search.api.model.response.channel.ChannelCommoditySearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * 装修服务实现类
 *
 * @author fhj
 * @version 2.0.0
 * @date 2021/8/23
 */
@Slf4j
@Service
public class AdornServiceImpl implements IAdornService {

    @Resource
    private MerchantActivityRepository merchantActivityRepository;
    @Resource
    private PlatformActivityRepository platformActivityRepository;
    @Resource
    private ActivityShopRepository shopRepository;
    @Resource
    private JPAQueryFactory queryFactory;
    @Resource
    private ActivityGoodsRepository goodsRepository;
    @Resource
    private ActivityGoodsSubsidiaryRepository goodsSubsidiaryRepository;
    @Resource
    private ITemplateFeign templateFeign;
    @Resource
    private ITemplateChannelFeign templateChannelFeign;
    @Resource
    private ActivityGoodsHandleComponent goodsHandleComponent;
    @Resource
    private IActivityOrderService activityOrderService;
    @Resource
    private BaseActivityService baseActivityService;
    @Resource
    private ISearchFeign searchFeign;

    /**
     * 平台营销活动列表（装修）
     */
    @Override
    public Wrapper<PageData<PfActivityListAdornResp>> platformActivityListAdorn(UserLoginCacheDTO user, PfActivityListAdornReq req) {
        //如果搜索参数中的商品名称或商家名称或品类ID有一个不为空，则根据搜索参数查询活动商品且去重拿到活动ID集合
        List<Long> activityIdList = new ArrayList<>();
        List<Long> goodsIdList = new ArrayList<>();
        if (!ObjectUtil.isAllEmpty(req.getMerchantName(), req.getProductName(), req.getCategoryId())) {
            QActivityGoodsDO platformActivityGoodsDO = QActivityGoodsDO.activityGoodsDO;

            BooleanBuilder predicates = new BooleanBuilder();
            predicates.and(platformActivityGoodsDO.belongType.eq(BelongTypeEnum.PLATFORM.getCode()));
            predicates.and(platformActivityGoodsDO.auditStatus.eq(ActivityGoodsAuditStatusEnum.AGREE.getCode()));
            if (ObjectUtil.isNotEmpty(req.getMerchantName())) {
                predicates.and(platformActivityGoodsDO.memberName.like("%" + req.getMerchantName() + "%"));
            }
            if (ObjectUtil.isNotEmpty(req.getProductName())) {
                predicates.and(platformActivityGoodsDO.productName.like("%" + req.getProductName() + "%"));
            }
            if (req.getCategoryId() != null) {
                goodsIdList = goodsHandleComponent.getGoodsIdListByCategory(req.getCategoryId(), null, req.getShopId());
                if (CollectionUtil.isEmpty(goodsIdList)) {
                    return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
                }
                predicates.and(platformActivityGoodsDO.productId.in(goodsIdList));
            }

            activityIdList = queryFactory.select(platformActivityGoodsDO.activityId)
                    .from(platformActivityGoodsDO).where(predicates).distinct().fetch();

            if (CollectionUtil.isEmpty(activityIdList)) {
                return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
            }
        }

        //根据所属商城获取适用于商城的平台活动ID
        List<ActivityShopDO> pfActivityShopList = shopRepository.findByBelongTypeAndShopId(
                BelongTypeEnum.PLATFORM.getCode(),
                req.getShopId()
        );
        if (CollectionUtil.isEmpty(pfActivityShopList)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<Long> idList = pfActivityShopList.stream().map(ActivityShopDO::getActivityId).collect(Collectors.toList());

        //筛选活动id
        if (CollectionUtil.isNotEmpty(activityIdList)) {
            idList = idList.stream().filter(activityIdList::contains).collect(toList());
            if (CollectionUtil.isEmpty(idList)) {
                return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
            }
        }
        List<Long> finalIdList = idList;

        //组装查询条件
        Specification<PlatformActivityDO> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.in(root.get("outerStatus")).value(PlatformActivityOuterStatusEnum.ONGOING.getCode()));

            if (req.getStartTime() != null) {
                list.add(criteriaBuilder.greaterThan(root.get("startTime").as(Long.class), req.getStartTime()));
            }
            if (req.getEndTime() != null) {
                list.add(criteriaBuilder.lessThan(root.get("endTime").as(Long.class), req.getEndTime()));
            }
            if (StringUtils.hasLength(req.getActivityName())) {
                list.add(criteriaBuilder.like(root.get("activityName").as(String.class), "%" + req.getActivityName().trim() + "%"));
            }
            if (req.getId() != null) {
                list.add(criteriaBuilder.equal(root.get("id").as(Long.class), req.getId()));
            }
            if (req.getActivityType() != null) {
                list.add(criteriaBuilder.equal(root.get("activityType").as(Integer.class), req.getActivityType()));
            }
            if (req.getMinType() != null) {
                list.add(criteriaBuilder.equal(root.get("minType").as(Integer.class), req.getMinType()));
            }
            if (CollectionUtil.isNotEmpty(finalIdList)) {
                list.add(criteriaBuilder.in(root.get("id")).value(new HashSet<>(finalIdList)));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        //分页查询平台活动
        Pageable page = PageRequest.of(req.getCurrent() - 1, req.getPageSize(), Sort.by("startTime").descending());
        Page<PlatformActivityDO> result = platformActivityRepository.findAll(spec, page);
        if (CollectionUtil.isEmpty(result.getContent())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //根据平台活动ID查询平台活动商品
        List<ActivityGoodsDO> goodsDOList;
        if (req.getCategoryId() != null) {
            goodsDOList = goodsRepository.findByBelongTypeAndAuditStatusAndActivityIdInAndProductIdIn(
                    BelongTypeEnum.PLATFORM.getCode(),
                    ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                    result.getContent().stream().map(PlatformActivityDO::getId).collect(Collectors.toList()),
                    goodsIdList,
                    Sort.by("id")
            );
        } else {
            goodsDOList = goodsRepository.findByBelongTypeAndAuditStatusAndActivityIdIn(
                    BelongTypeEnum.PLATFORM.getCode(),
                    ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                    result.getContent().stream().map(PlatformActivityDO::getId).collect(Collectors.toList()),
                    Sort.by("id")
            );
        }

        //根据平台活动商品获取配套商品, 如果获取不到说明非此类型(赠品、换购商品、套餐)的活动
        List<Long> activityGoodsIds = goodsDOList.stream().map(ActivityGoodsDO::getId).collect(toList());

        //对配套商品进行组装
        Map<Long, List<PfActivityListAdornResp.PfActivityGoodsResp.PfActivityGoodsSubsidiaryGroupResp>> subsidiaryMap = getPfActivityGoodsSubsidiaryMap(activityGoodsIds);

        //根据活动商品ID，获取活动商品的赠品（优惠卷）
        Map<Long, List<Map<String, Object>>> activityGoodsGiveCoupon = getActivityGoodsGiveCouponMap(activityGoodsIds);

        //根据平台活动商品里的skuId再次获取出平台活动商品（可通过按sku分组后得到平台活动商品所关联的所有平台活动）
        List<ActivityGoodsDO> activityGoodsDOList = goodsRepository.findAllByBelongTypeAndAuditStatusAndSkuIdIn(
                BelongTypeEnum.PLATFORM.getCode(),
                ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                goodsDOList.stream().map(ActivityGoodsDO::getSkuId).collect(Collectors.toList())
        );

        //根据平台活动商品筛选出所属的平台活动
        List<PlatformActivityDO> pfActivityList = platformActivityRepository.findAllById(
                activityGoodsDOList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toSet())
        );

        //组装活动商品
        Map<Long, List<PfActivityListAdornResp.PfActivityGoodsResp>> goodsMap = goodsDOList.stream().map(goods -> {
            //拷贝
            PfActivityListAdornResp.PfActivityGoodsResp goodsResp = new PfActivityListAdornResp.PfActivityGoodsResp();
            BeanUtils.copyProperties(goods, goodsResp);

            //根据skuId筛选出活动ID
            List<Long> ids = activityGoodsDOList.stream().filter(a ->
                    a.getSkuId().equals(goods.getSkuId())
            ).map(ActivityGoodsDO::getActivityId).collect(Collectors.toList());

            //封装所属活动
            if (CollectionUtil.isNotEmpty(ids)) {
                goodsResp.setActivityList(
                        pfActivityList.stream().filter(a ->
                                ids.contains(a.getId())
                        ).map(pfActivity -> {
                            Map<String, Object> m = new HashMap<>();
                            m.put("id", pfActivity.getId());
                            m.put("type", ActivityTypeEnum.getMessage(pfActivity.getActivityType()));
                            m.put("name", pfActivity.getActivityName());
                            m.put("belongType", BelongTypeEnum.PLATFORM.getCode());
                            //判断有没有标签
                            if (PlatformActivityOuterStatusEnum.ONGOING.getCode().equals(pfActivity.getOuterStatus())
                                    && pfActivity.getStartTime() < System.currentTimeMillis()
                                    && pfActivity.getEndTime() > System.currentTimeMillis()) {
                                if (pfActivity.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                                    m.put("label", MarketingFieldsEnum.FALL.getMessage() + goods.getPlummetPrice());
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                                    m.put("label", goods.getDiscount() + MarketingFieldsEnum.FOLD_UP.getMessage());
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                                    FullQuantityBO fullQuantityBO = (FullQuantityBO) pfActivity.getActivityDefined();
                                    if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                        fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage()));
                                    } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                        fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.FOLD.getMessage()));
                                    }
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                                    FullMoneyBO fullMoneyBO = (FullMoneyBO) pfActivity.getActivityDefined();
                                    if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                        fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage()));
                                    } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                        fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.FOLD.getMessage()));
                                    }
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                                    MorePieceBO morePieceBO = (MorePieceBO) pfActivity.getActivityDefined();
                                    morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getDiscount() + MarketingFieldsEnum.FOLD.getMessage()));
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                                    CombinationBO combinationBO = (CombinationBO) pfActivity.getActivityDefined();
                                    m.put("label", combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                                    m.put("label", MarketingFieldsEnum.REDEMPTION.getMessage());
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                                    m.put("label", MarketingFieldsEnum.EARNEST_MONEY.getMessage() + goods.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + goods.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
                                } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                                    //获取拼团人数
                                    PlatformActivityDO platformActivityDO = platformActivityRepository.findById(pfActivity.getId()).orElse(null);
                                    if (!Objects.isNull(platformActivityDO)) {
                                        JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.PLATFORM, platformActivityDO.getActivityType(), platformActivityDO.getActivityDefined());
                                        m.put("label", jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
                                    }
                                }
                            } else {
                                m.put("label", "");
                            }
                            return m;
                        }).collect(Collectors.toList())
                );
            }

            //封装配套商品
            if (CollectionUtil.isNotEmpty(subsidiaryMap)) {
                goodsResp.setGoodsSubsidiaryGroupList(subsidiaryMap.get(goods.getId()));
            }

            //封装赠品（优惠卷）
            if (CollectionUtil.isNotEmpty(activityGoodsGiveCoupon)) {
                goodsResp.setGiveCouponList(activityGoodsGiveCoupon.get(goods.getId()));
            }

            return goodsResp;
        }).collect(Collectors.groupingBy(PfActivityListAdornResp.PfActivityGoodsResp::getActivityId));

        //组装活动和活动内商品
        List<PfActivityListAdornResp> resultList = result.getContent().stream().map(o -> {
            PfActivityListAdornResp resp = new PfActivityListAdornResp();
            BeanUtils.copyProperties(o, resp);
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(o.getActivityType()));
            resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(o.getOuterStatus()));
            resp.setGoodsList(goodsMap.get(resp.getId()));
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(result.getTotalElements(), resultList));
    }

    /**
     * 商家营销活动列表（装修）
     **/
    @Override
    public Wrapper<PageData<McActivityListAdornResp>> merchantActivityListAdorn(UserLoginCacheDTO user, McActivityListAdornReq req) {
        //处理数据BigDecimal 专用
        DecimalFormat decimalFormat = new DecimalFormat("##########.##########");
        //如果搜索参数中的商品名称或品类ID有一个不为空，则根据搜索参数查询活动商品且去重拿到活动ID集合
        List<Long> activityIdList = new ArrayList<>();
        List<Long> goodsIdList = new ArrayList<>();
        if (!ObjectUtil.isAllEmpty(req.getProductName(), req.getCategoryId())) {
            QActivityGoodsDO platformActivityGoodsDO = QActivityGoodsDO.activityGoodsDO;

            BooleanBuilder predicates = new BooleanBuilder();
            predicates.and(platformActivityGoodsDO.belongType.eq(BelongTypeEnum.MERCHANT.getCode()));
            predicates.and(platformActivityGoodsDO.auditStatus.eq(ActivityGoodsAuditStatusEnum.AGREE.getCode()));
            if (ObjectUtil.isNotEmpty(req.getProductName())) {
                predicates.and(platformActivityGoodsDO.productName.like("%" + req.getProductName() + "%"));
            }
            if (req.getCategoryId() != null) {
                goodsIdList = goodsHandleComponent.getGoodsIdListByCategory(null, req.getCategoryId(), req.getShopId());
                if (CollectionUtil.isEmpty(goodsIdList)) {
                    return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
                }
                predicates.and(platformActivityGoodsDO.productId.in(goodsIdList));
            }

            activityIdList = queryFactory.select(platformActivityGoodsDO.activityId)
                    .from(platformActivityGoodsDO).where(predicates).distinct().fetch();

            if (CollectionUtil.isEmpty(activityIdList)) {
                return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
            }
        }

        //根据所属商城获取适用于商城的商家活动ID
        List<ActivityShopDO> mcActivityShopList = shopRepository.findByBelongTypeAndShopId(
                BelongTypeEnum.MERCHANT.getCode(),
                req.getShopId()
        );
        if (CollectionUtil.isEmpty(mcActivityShopList)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<Long> idList = mcActivityShopList.stream().map(ActivityShopDO::getActivityId).collect(Collectors.toList());

        //筛选活动id
        if (CollectionUtil.isNotEmpty(activityIdList)) {
            idList = idList.stream().filter(activityIdList::contains).collect(toList());
            if (CollectionUtil.isEmpty(idList)) {
                return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
            }
        }
        List<Long> finalIdList = idList;

        //组装查询条件
        Specification<MerchantActivityDO> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.in(root.get("innerStatus")).value(MerchantActivityInnerStatusEnum.ONGOING.getCode()));
            list.add(criteriaBuilder.in(root.get("memberId")).value(user.getMemberId()));
            list.add(criteriaBuilder.in(root.get("roleId")).value(user.getMemberRoleId()));

            if (req.getStartTime() != null) {
                list.add(criteriaBuilder.greaterThan(root.get("startTime").as(Long.class), req.getStartTime()));
            }
            if (req.getEndTime() != null) {
                list.add(criteriaBuilder.lessThan(root.get("endTime").as(Long.class), req.getEndTime()));
            }
            if (StringUtils.hasLength(req.getActivityName())) {
                list.add(criteriaBuilder.like(root.get("activityName").as(String.class), "%" + req.getActivityName().trim() + "%"));
            }
            if (req.getId() != null) {
                list.add(criteriaBuilder.equal(root.get("id").as(Long.class), req.getId()));
            }
            if (req.getActivityType() != null) {
                list.add(criteriaBuilder.equal(root.get("activityType").as(Integer.class), req.getActivityType()));
            }
            if (req.getMinType() != null) {
                list.add(criteriaBuilder.equal(root.get("minType").as(Integer.class), req.getMinType()));
            }
            if (CollectionUtil.isNotEmpty(finalIdList)) {
                list.add(criteriaBuilder.in(root.get("id")).value(new HashSet<>(finalIdList)));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        //分页查询商家活动
        Pageable page = PageRequest.of(req.getCurrent() - 1, req.getPageSize(), Sort.by("startTime").descending());
        Page<MerchantActivityDO> result = merchantActivityRepository.findAll(spec, page);
        if (CollectionUtil.isEmpty(result.getContent())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //根据商家活动ID查询商家活动商品
        List<ActivityGoodsDO> goodsDOList;
        if (req.getCategoryId() != null) {
            goodsDOList = goodsRepository.findByBelongTypeAndAuditStatusAndActivityIdInAndProductIdIn(
                    BelongTypeEnum.MERCHANT.getCode(),
                    ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                    result.getContent().stream().map(MerchantActivityDO::getId).collect(Collectors.toList()),
                    goodsIdList,
                    Sort.by("id")
            );
        } else {
            goodsDOList = goodsRepository.findByBelongTypeAndAuditStatusAndActivityIdIn(
                    BelongTypeEnum.MERCHANT.getCode(),
                    ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                    result.getContent().stream().map(MerchantActivityDO::getId).collect(Collectors.toList()),
                    Sort.by("id")
            );
        }

        //根据商家活动商品获取配套商品, 如果获取不到说明非此类型(赠品、换购商品、套餐)的活动
        List<Long> activityGoodsIds = goodsDOList.stream().map(ActivityGoodsDO::getId).collect(toList());

        //对配套商品进行组装
        Map<Long, List<McActivityListAdornResp.McActivityGoodsResp.McActivityGoodsSubsidiaryGroupResp>> subsidiaryMap = getMcActivityGoodsSubsidiaryMap(activityGoodsIds);

        //根据活动商品ID，获取活动商品的赠品（优惠卷）
        Map<Long, List<Map<String, Object>>> activityGoodsGiveCoupon = getActivityGoodsGiveCouponMap(activityGoodsIds);

        //根据商家活动商品里的skuId再次获取出商家活动商品（可通过按sku分组后得到商家活动商品所关联的所有商家活动）
        List<ActivityGoodsDO> activityGoodsDOList = goodsRepository.findAllByBelongTypeAndAuditStatusAndSkuIdIn(
                BelongTypeEnum.MERCHANT.getCode(),
                ActivityGoodsAuditStatusEnum.AGREE.getCode(),
                goodsDOList.stream().map(ActivityGoodsDO::getSkuId).collect(Collectors.toList())
        );

        //根据商家活动商品筛选出所属的商家活动
        List<MerchantActivityDO> mcActivityList = merchantActivityRepository.findAllById(
                activityGoodsDOList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toSet())
        );

        //组装活动商品
        Map<Long, List<McActivityListAdornResp.McActivityGoodsResp>> goodsMap = goodsDOList.stream().map(goods -> {
            //拷贝
            McActivityListAdornResp.McActivityGoodsResp goodsResp = new McActivityListAdornResp.McActivityGoodsResp();
            BeanUtils.copyProperties(goods, goodsResp);

            //根据skuId筛选出活动ID
            List<Long> ids = activityGoodsDOList.stream().filter(a ->
                    a.getSkuId().equals(goods.getSkuId())
            ).map(ActivityGoodsDO::getActivityId).collect(Collectors.toList());

            //封装所属活动
            if (CollectionUtil.isNotEmpty(ids)) {
                goodsResp.setActivityList(
                        mcActivityList.stream().filter(a ->
                                ids.contains(a.getId())
                        ).map(mcActivity -> {
                            Map<String, Object> m = new HashMap<>();
                            m.put("id", mcActivity.getId());
                            m.put("type", ActivityTypeEnum.getMessage(mcActivity.getActivityType()));
                            m.put("name", mcActivity.getActivityName());
                            m.put("belongType", BelongTypeEnum.MERCHANT.getCode());
                            //判断有没有标签
                            if (MerchantActivityInnerStatusEnum.ONGOING.getCode().equals(mcActivity.getInnerStatus())
                                    && mcActivity.getStartTime() < System.currentTimeMillis()
                                    && mcActivity.getEndTime() > System.currentTimeMillis()) {
                                if (mcActivity.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                                    m.put("label", MarketingFieldsEnum.FALL.getMessage() + goods.getPlummetPrice());
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                                    m.put("label", goods.getDiscount() + MarketingFieldsEnum.FOLD_UP.getMessage());
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                                    FullQuantityBO fullQuantityBO = (FullQuantityBO) mcActivity.getActivityDefined();
                                    if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                        FullQuantityBO.LadderBO ladderBO = fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).orElse(null);
                                        if (ladderBO != null) {
                                            goodsResp.setActivityPrice(goods.getActivityPrice() != null ? goods.getActivityPrice().compareTo(new BigDecimal(0)) > 0 ? goods.getActivityPrice() : goods.getPrice().subtract(ladderBO.getValue()) : goods.getPrice().subtract(ladderBO.getValue()));
                                            m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                                        }
                                    } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                        fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.FOLD.getMessage()));
                                    }
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                                    FullMoneyBO fullMoneyBO = (FullMoneyBO) mcActivity.getActivityDefined();
                                    if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                                        FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                                        if (ladderBO != null) {
                                            goodsResp.setActivityPrice(goods.getActivityPrice() != null ? goods.getActivityPrice().compareTo(new BigDecimal(0)) > 0 ? goods.getActivityPrice() : goods.getPrice().subtract(ladderBO.getValue()) : goods.getPrice().subtract(ladderBO.getValue()));
                                            m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage());
                                        }
                                    } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                                        FullMoneyBO.LadderBO ladderBO = fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).orElse(null);
                                        if (ladderBO != null) {
                                            goodsResp.setActivityPrice(goods.getActivityPrice() != null ? goods.getActivityPrice().compareTo(new BigDecimal(0)) > 0 ? goods.getActivityPrice() : goods.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))) : goods.getPrice().multiply(ladderBO.getValue().multiply(BigDecimal.valueOf(0.01))));
                                            m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + decimalFormat.format(ladderBO.getValue().multiply(new BigDecimal("0.1"))) + MarketingFieldsEnum.FOLD.getMessage());
                                        }
                                    }
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                                    MorePieceBO morePieceBO = (MorePieceBO) mcActivity.getActivityDefined();
                                    morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getDiscount() + MarketingFieldsEnum.FOLD.getMessage()));
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                                    CombinationBO combinationBO = (CombinationBO) mcActivity.getActivityDefined();
                                    m.put("label", combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                                    m.put("label", MarketingFieldsEnum.REDEMPTION.getMessage());
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                                    m.put("label", MarketingFieldsEnum.EARNEST_MONEY.getMessage() + goods.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + goods.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
                                } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                                    //获取拼团人数
                                    MerchantActivityDO merchantActivityDO = merchantActivityRepository.findById(mcActivity.getId()).orElse(null);
                                    if (!Objects.isNull(merchantActivityDO)) {
                                        JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.MERCHANT, merchantActivityDO.getActivityType(), merchantActivityDO.getActivityDefined());
                                        m.put("label", jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
                                    }
                                }
                            } else {
                                m.put("label", "");
                            }
                            return m;
                        }).collect(Collectors.toList())
                );
            }

            //封装配套商品
            if (CollectionUtil.isNotEmpty(subsidiaryMap)) {
                goodsResp.setGoodsSubsidiaryGroupList(subsidiaryMap.get(goods.getId()));
            }

            //封装赠品（优惠卷）
            if (CollectionUtil.isNotEmpty(activityGoodsGiveCoupon)) {
                goodsResp.setGiveCouponList(activityGoodsGiveCoupon.get(goods.getId()));
            }

            return goodsResp;
        }).

                collect(Collectors.groupingBy(McActivityListAdornResp.McActivityGoodsResp::getActivityId));

        //组装活动和活动内商品
        List<McActivityListAdornResp> resultList = result.getContent().stream().map(o -> {
            McActivityListAdornResp resp = new McActivityListAdornResp();
            BeanUtils.copyProperties(o, resp);
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(o.getActivityType()));
            resp.setOuterStatusName(MerchantActivityInnerStatusEnum.getMessage(o.getInnerStatus()));
            resp.setGoodsList(goodsMap.get(resp.getId()));

            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(result.getTotalElements(), resultList));
    }

    /**
     * 回显活动商品（装修）
     **/
    @Override
    public Wrapper<List<ActivityGoodsAdornResp>> activityGoodsAdorn(ActivityGoodsAdornReq req) {
        //获取活动商品
        List<ActivityGoodsDO> goodsDOList = goodsRepository.findAllById(req.getIds());
        if (CollectionUtil.isEmpty(goodsDOList)) {
            return Wrapper.success(new ArrayList<>());//没有活动商品时直接返回空数组
        }
        List<Long> skuIds = goodsDOList.stream().map(ActivityGoodsDO::getSkuId).collect(toList());
        //根据区域赛选数据
        if (req.getProvinceCode() != null && req.getCityCode() != null) {
            CommoditySkuRequest request = new CommoditySkuRequest();
            request.setProvinceCode(req.getProvinceCode());
            request.setCityCode(req.getCityCode());
            request.setSkuIdInList(skuIds);
            Wrapper<List<CommoditySkuResponse>> commoditySkuList = searchFeign.getCommoditySkuList(request);
            List<CommoditySkuResponse> responseList = commoditySkuList.getData();
            if (!CollectionUtils.isEmpty(responseList)) {
                List<Long> list = responseList.stream().map(CommoditySkuResponse::getId).collect(toList());
                goodsDOList = goodsDOList.stream().filter(e -> list.contains(e.getSkuId())).collect(toList());
            }
        }

        //根据活动商品获取配套商品, 如果获取不到说明非此类型(赠品、换购商品、套餐)的活动
        List<Long> activityGoodsIds = goodsDOList.stream().map(ActivityGoodsDO::getId).collect(toList());

        //对配套商品进行组装
        Map<Long, List<ActivityGoodsAdornResp.ActivityGoodsSubsidiaryGroupResp>> subsidiaryMap = getActivityGoodsSubsidiaryMap(activityGoodsIds);

        //根据活动商品ID，获取活动商品的赠品（优惠卷）
        Map<Long, List<Map<String, Object>>> activityGoodsGiveCoupon = getActivityGoodsGiveCouponMap(activityGoodsIds);

        //根据活动商品里的skuId再次获取出活动商品（会有多个相同的活动商品但对应了不同的活动）
        List<ActivityGoodsDO> skuList = goodsRepository.findAllBySkuIdIn(
                goodsDOList.stream().map(ActivityGoodsDO::getSkuId).collect(Collectors.toList())
        );
        //从活动商品里筛选出平台活动的活动商品
        List<ActivityGoodsDO> pfActivityGoodsList = skuList.stream().filter(a ->
                a.getBelongType().equals(BelongTypeEnum.PLATFORM.getCode())
        ).collect(Collectors.toList());
        //从活动商品里筛选出商家活动的活动商品
        List<ActivityGoodsDO> mcActivityGoodsList = skuList.stream().filter(a ->
                a.getBelongType().equals(BelongTypeEnum.MERCHANT.getCode())
        ).collect(Collectors.toList());
        //根据活动商品查出活动进行的平台活动
        List<PlatformActivityDO> pfActivityList = platformActivityRepository.findAllByIdInAndOuterStatus(
                pfActivityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toList()),
                PlatformActivityOuterStatusEnum.ONGOING.getCode()
        );
        //根据活动商品查出活动进行的商家活动
        List<MerchantActivityDO> mcActivityList = merchantActivityRepository.findAllByIdInAndInnerStatus(
                mcActivityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toList()),
                MerchantActivityInnerStatusEnum.ONGOING.getCode()
        );
        //根据skuID分组，获取每个商品所关联的平台活动ID
        Map<Long, List<Long>> pfActivityMap = pfActivityGoodsList.stream().collect(Collectors.groupingBy(
                ActivityGoodsDO::getSkuId, Collectors.mapping(ActivityGoodsDO::getActivityId, Collectors.toList())
        ));
        //根据skuID分组，获取每个商品所关联的商家活动ID
        Map<Long, List<Long>> mcActivityMap = mcActivityGoodsList.stream().collect(Collectors.groupingBy(
                ActivityGoodsDO::getSkuId, Collectors.mapping(ActivityGoodsDO::getActivityId, Collectors.toList())
        ));

        //组装活动商品数据且按参数ids进行排序
        List<ActivityGoodsAdornResp> result = goodsDOList.stream().sorted(Comparator.comparingInt(goods ->
                req.getIds().indexOf(goods.getId()))
        ).map(goods -> {
            //拷贝活动商品数据
            ActivityGoodsAdornResp goodsAdornResp = new ActivityGoodsAdornResp();
            BeanUtils.copyProperties(goods, goodsAdornResp);

            //封装配套商品
            if (CollectionUtil.isNotEmpty(subsidiaryMap)) {
                goodsAdornResp.setGoodsSubsidiaryGroupList(subsidiaryMap.get(goods.getId()));
            }

            //封装赠品（优惠卷）
            if (CollectionUtil.isNotEmpty(activityGoodsGiveCoupon)) {
                goodsAdornResp.setGiveCouponList(activityGoodsGiveCoupon.get(goods.getId()));
            }

            //封装商品所关联的平台活动
            if (CollectionUtil.isNotEmpty(pfActivityMap)) {
                List<Map<String, Object>> activityList = pfActivityList.stream().filter(a ->
                        CollectionUtil.isNotEmpty(pfActivityMap.get(goods.getSkuId()))
                                && pfActivityMap.get(goods.getSkuId()).contains(a.getId())
                ).map(pfActivity -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("id", pfActivity.getId());
                    m.put("type", ActivityTypeEnum.getMessage(pfActivity.getActivityType()));
                    m.put("name", pfActivity.getActivityName());
                    m.put("belongType", BelongTypeEnum.PLATFORM.getCode());
                    //判断有没有标签
                    if (pfActivity.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                        m.put("label", MarketingFieldsEnum.FALL.getMessage() + goods.getPlummetPrice());
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                        m.put("label", goods.getDiscount() + MarketingFieldsEnum.FOLD_UP.getMessage());
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                        FullQuantityBO fullQuantityBO = (FullQuantityBO) pfActivity.getActivityDefined();
                        if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                            fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage()));
                        } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                            fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.FOLD.getMessage()));
                        }
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                        FullMoneyBO fullMoneyBO = (FullMoneyBO) pfActivity.getActivityDefined();
                        if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                            fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage()));
                        } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                            fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.FOLD.getMessage()));
                        }
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                        MorePieceBO morePieceBO = (MorePieceBO) pfActivity.getActivityDefined();
                        morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getDiscount() + MarketingFieldsEnum.FOLD.getMessage()));
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                        CombinationBO combinationBO = (CombinationBO) pfActivity.getActivityDefined();
                        m.put("label", combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                        m.put("label", MarketingFieldsEnum.REDEMPTION.getMessage());
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                        m.put("label", MarketingFieldsEnum.EARNEST_MONEY.getMessage() + goods.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + goods.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
                    } else if (pfActivity.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                        //获取拼团人数
                        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(pfActivity.getId()).orElse(null);
                        if (!Objects.isNull(platformActivityDO)) {
                            JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.PLATFORM, platformActivityDO.getActivityType(), platformActivityDO.getActivityDefined());
                            m.put("label", jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
                        } else {
                            m.put("label", "");
                        }
                    } else {
                        m.put("label", "");
                    }

                    return m;
                }).collect(Collectors.toList());
                goodsAdornResp.setActivityList(activityList);
            }

            //封装商品所关联的商家活动
            if (CollectionUtil.isNotEmpty(mcActivityMap)) {
                List<Map<String, Object>> activityList = mcActivityList.stream().filter(a ->
                        CollectionUtil.isNotEmpty(mcActivityMap.get(goods.getSkuId()))
                                && mcActivityMap.get(goods.getSkuId()).contains(a.getId())
                ).map(mcActivity -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("id", mcActivity.getId());
                    m.put("type", ActivityTypeEnum.getMessage(mcActivity.getActivityType()));
                    m.put("name", mcActivity.getActivityName());
                    m.put("belongType", BelongTypeEnum.MERCHANT.getCode());
                    //判断有没有标签
                    if (mcActivity.getActivityType().equals(ActivityTypeEnum.PLUMMET.getCode())) {
                        m.put("label", MarketingFieldsEnum.FALL.getMessage() + goods.getPlummetPrice());
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.DISCOUNT.getCode())) {
                        m.put("label", goods.getDiscount() + MarketingFieldsEnum.FOLD_UP.getMessage());
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.FULL_QUANTITY.getCode())) {
                        FullQuantityBO fullQuantityBO = (FullQuantityBO) mcActivity.getActivityDefined();
                        if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                            fullQuantityBO.getLadderList().stream().max(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.PIECE_MINUS.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage()));
                        } else if (fullQuantityBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                            fullQuantityBO.getLadderList().stream().min(Comparator.comparing(FullQuantityBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.FOLD.getMessage()));
                        }
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.FULL_MONEY.getCode())) {
                        FullMoneyBO fullMoneyBO = (FullMoneyBO) mcActivity.getActivityDefined();
                        if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.REDUCTION.getCode())) {
                            fullMoneyBO.getLadderList().stream().max(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.REDUCE.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.YUAN.getMessage()));


                        } else if (fullMoneyBO.getType().equals(FullQuantityTypeEnum.DISCOUNT.getCode())) {
                            fullMoneyBO.getLadderList().stream().min(Comparator.comparing(FullMoneyBO.LadderBO::getValue)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.FULL.getMessage() + ladderBO.getKey() + MarketingFieldsEnum.YUAN.getMessage() + ladderBO.getValue() + MarketingFieldsEnum.FOLD.getMessage()));
                        }
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.MORE_PIECE.getCode())) {
                        MorePieceBO morePieceBO = (MorePieceBO) mcActivity.getActivityDefined();
                        morePieceBO.getLadderList().stream().min(Comparator.comparing(MorePieceBO.LadderBO::getDiscount)).ifPresent(ladderBO -> m.put("label", MarketingFieldsEnum.THE_FIRST.getMessage() + ladderBO.getNum() + MarketingFieldsEnum.ITEM.getMessage() + ladderBO.getDiscount() + MarketingFieldsEnum.FOLD.getMessage()));
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.COMBINATION.getCode())) {
                        CombinationBO combinationBO = (CombinationBO) mcActivity.getActivityDefined();
                        m.put("label", combinationBO.getPrice() + MarketingFieldsEnum.YUAN.getMessage() + combinationBO.getNum() + MarketingFieldsEnum.ITEM.getMessage());
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.SWAP.getCode())) {
                        m.put("label", MarketingFieldsEnum.REDEMPTION.getMessage());
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.PRE_SALE.getCode())) {
                        m.put("label", MarketingFieldsEnum.EARNEST_MONEY.getMessage() + goods.getActivityPrice() + MarketingFieldsEnum.YUAN_ARRIVES.getMessage() + goods.getDeductionPrice() + MarketingFieldsEnum.YUAN.getMessage());
                    } else if (mcActivity.getActivityType().equals(ActivityTypeEnum.GROUP_PURCHASE.getCode())) {
                        //获取拼团人数
                        MerchantActivityDO merchantActivityDO = merchantActivityRepository.findById(mcActivity.getId()).orElse(null);
                        if (!Objects.isNull(merchantActivityDO)) {
                            JSONObject jsonObject = baseActivityService.getActivityDefine(BelongTypeEnum.MERCHANT, merchantActivityDO.getActivityType(), merchantActivityDO.getActivityDefined());
                            m.put("label", jsonObject.get("assembleNum") + MarketingFieldsEnum.GROUP_OF_PEOPLE.getMessage());
                        } else {
                            m.put("label", "");
                        }
                    } else {
                        m.put("label", "");
                    }
                    return m;
                }).collect(Collectors.toList());
                goodsAdornResp.getActivityList().addAll(activityList);
            }

            return goodsAdornResp;
        }).collect(Collectors.toList());

        return Wrapper.success(result);
    }

    /**
     * 商品列表（装修）
     **/
    @Override
    public Wrapper<PageData<GoodsListAdornResp>> goodsListAdorn(GoodsListAdornReq req) {
        //调用搜索服务 -> 获取商品信息
        TemplateCommoditySearchRequest searchRequest = new TemplateCommoditySearchRequest();
        searchRequest.setCurrent(req.getCurrent());
        searchRequest.setPageSize(req.getPageSize());
        searchRequest.setShopId(req.getShopId());
        searchRequest.setCategoryId(req.getCategoryId());
        searchRequest.setCustomerCategoryId(req.getCustomerCategoryId());
        searchRequest.setBrandId(req.getBrandId());
        searchRequest.setMemberName(req.getMemberName());
        searchRequest.setName(req.getName());
        searchRequest.setPublishStartTime(req.getPublishStartTime());
        searchRequest.setPublishEndTime(req.getPublishEndTime());
        searchRequest.setMemberId(req.getMemberId());
        searchRequest.setMemberRoleId(req.getMemberRoleId());
        searchRequest.setProvinceCode(req.getProvinceCode());
        searchRequest.setCityCode(req.getCityCode());
        if (StringUtils.hasLength(req.getIdNotInList())) {
            String[] split = req.getIdNotInList().split(",");
            List<String> asList = Arrays.asList(split);
            List<Long> collect = asList.stream().map(s -> Long.parseLong(s.trim())).collect(toList());
            searchRequest.setIdNotInList(collect);
        }
        if (StringUtils.hasLength(req.getIdInList())) {
            String[] split = req.getIdInList().split(",");
            List<String> asList = Arrays.asList(split);
            List<Long> collect = asList.stream().map(s -> Long.parseLong(s.trim())).collect(toList());
            searchRequest.setIdInList(collect);
        }
        searchRequest.setPriceTypeList(Stream.of(PriceTypeEnum.Cash.getCode()).collect(Collectors.toList()));
        Wrapper<PageData<CommoditySearchResponse>> wrapper = templateFeign.searchCommodityList(searchRequest);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (wrapper.getData().getTotalCount().equals(0L)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //从搜索服务获取到的商品数据
        List<CommoditySearchResponse> goodsList = wrapper.getData().getData();

        //拼装
        List<GoodsListAdornResp> respList = goodsList.stream().map(a -> {
            GoodsListAdornResp resp = new GoodsListAdornResp();
            BeanUtils.copyProperties(a, resp);
            if (a.getPreferentialPrice() != null && a.getPreferentialPrice().compareTo(new BigDecimal(0)) > 0) {
                resp.setMin(Double.valueOf(a.getPreferentialPrice() + ""));
            }
            return resp;
        }).collect(Collectors.toList());

        //根据商品ID获取活动商品
        List<ActivityGoodsDO> activityGoodsDOList = goodsRepository.findAllByProductIdIn(
                goodsList.stream().map(CommoditySearchResponse::getId).collect(Collectors.toList())
        );

        //组装商品所拥有的平台活动和商家活动
        if (CollectionUtil.isNotEmpty(activityGoodsDOList)) {
            //从活动商品里筛选出平台活动的活动商品
            List<ActivityGoodsDO> pfActivityGoodsList = activityGoodsDOList.stream().filter(a ->
                    a.getBelongType().equals(BelongTypeEnum.PLATFORM.getCode())
            ).collect(Collectors.toList());
            //从活动商品里筛选出商家活动的活动商品
            List<ActivityGoodsDO> mcActivityGoodsList = activityGoodsDOList.stream().filter(a ->
                    a.getBelongType().equals(BelongTypeEnum.MERCHANT.getCode())
            ).collect(Collectors.toList());

            //根据活动商品查出活动进行的平台活动
            List<PlatformActivityDO> pfActivityList = platformActivityRepository.findAllByIdInAndOuterStatus(
                    pfActivityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toList()),
                    PlatformActivityOuterStatusEnum.ONGOING.getCode()
            );
            //根据活动商品查出活动进行的商家活动
            List<MerchantActivityDO> mcActivityList = merchantActivityRepository.findAllByIdInAndInnerStatus(
                    mcActivityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toList()),
                    MerchantActivityInnerStatusEnum.ONGOING.getCode()
            );

            //根据商品ID分组，获取每个商品所关联的平台活动ID
            Map<Long, List<Long>> pfActivityMap = pfActivityGoodsList.stream().collect(Collectors.groupingBy(
                    ActivityGoodsDO::getProductId, Collectors.mapping(ActivityGoodsDO::getActivityId, Collectors.toList())
            ));

            //根据商品ID分组，获取每个商品所关联的商家活动ID
            Map<Long, List<Long>> mcActivityMap = mcActivityGoodsList.stream().collect(Collectors.groupingBy(
                    ActivityGoodsDO::getProductId, Collectors.mapping(ActivityGoodsDO::getActivityId, Collectors.toList())
            ));

            //组装
            respList.forEach(resp -> {
                //封装商品所关联的平台活动
                if (CollectionUtil.isNotEmpty(pfActivityMap)) {
                    List<Map<String, Object>> activityList = pfActivityList.stream().filter(a ->
                            CollectionUtil.isNotEmpty(pfActivityMap.get(resp.getId()))
                                    && pfActivityMap.get(resp.getId()).contains(a.getId())
                    ).map(pfActivity -> {
                        Map<String, Object> m = new HashMap<>();
                        m.put("id", pfActivity.getId());
                        m.put("type", ActivityTypeEnum.getMessage(pfActivity.getActivityType()));
                        m.put("name", pfActivity.getActivityName());
                        m.put("belongType", BelongTypeEnum.PLATFORM.getCode());
                        m.put("startTime", pfActivity.getStartTime());
                        m.put("endTime", pfActivity.getEndTime());
                        return m;
                    }).collect(Collectors.toList());
                    resp.setActivityList(activityList);
                }

                //封装商品所关联的商家活动
                if (CollectionUtil.isNotEmpty(mcActivityMap)) {
                    List<Map<String, Object>> activityList = mcActivityList.stream().filter(a ->
                            CollectionUtil.isNotEmpty(mcActivityMap.get(resp.getId()))
                                    && mcActivityMap.get(resp.getId()).contains(a.getId())
                    ).map(mcActivity -> {
                        Map<String, Object> m = new HashMap<>();
                        m.put("id", mcActivity.getId());
                        m.put("type", ActivityTypeEnum.getMessage(mcActivity.getActivityType()));
                        m.put("name", mcActivity.getActivityName());
                        m.put("belongType", BelongTypeEnum.MERCHANT.getCode());
                        m.put("startTime", mcActivity.getStartTime());
                        m.put("endTime", mcActivity.getEndTime());
                        return m;
                    }).collect(Collectors.toList());
                    resp.getActivityList().addAll(activityList);
                }
            });
        }

        //如果包含ID参数不为空则按商品ID排下序
        if (StringUtils.hasLength(req.getIdInList())) {
            respList = respList.stream().sorted(Comparator.comparingInt(a -> req.getIdInList().indexOf(Math.toIntExact(a.getId())))).collect(toList());
        }
        return Wrapper.success(new PageData<>(wrapper.getData().getTotalCount(), respList));
    }


    /**
     * 渠道商品列表（装修）
     **/
    @Override
    public Wrapper<PageData<ChannelGoodsListAdornResp>> channelGoodsListAdorn(ChannelGoodsListAdornReq req) {
        //校验
        if (CollectionUtil.isNotEmpty(req.getIdNotInList()) && CollectionUtil.isNotEmpty(req.getIdInList())) {
            return Wrapper.fail(ResponseCode.MARKETING_PARAMETER_CONFLICT);
        }
        //调用搜索服务 -> 获取渠道商品信息
        TemplateChannelCommoditySearchRequest searchRequest = new TemplateChannelCommoditySearchRequest();
        searchRequest.setCurrent(req.getCurrent());
        searchRequest.setPageSize(req.getPageSize());
        searchRequest.setShopId(req.getShopId());
        searchRequest.setCustomerCategoryId(req.getCustomerCategoryId());
        searchRequest.setBrandId(req.getBrandId());
        searchRequest.setMemberId(req.getMemberId());
        searchRequest.setMemberRoleId(req.getMemberRoleId());
        searchRequest.setName(req.getName());
        searchRequest.setIdInList(req.getIdInList());
        searchRequest.setIdNotInList(req.getIdNotInList());
        searchRequest.setProvinceCode(req.getProvinceCode());
        searchRequest.setCityCode(req.getCityCode());
        Wrapper<PageData<ChannelCommoditySearchResponse>> wrapper = templateChannelFeign.searchCommodityList(searchRequest);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (wrapper.getData().getTotalCount().equals(0L)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //从搜索服务获取到的商品数据
        List<ChannelCommoditySearchResponse> goodsList = wrapper.getData().getData();

        //拼装
        List<ChannelGoodsListAdornResp> respList = goodsList.stream().map(a -> {
            ChannelGoodsListAdornResp resp = new ChannelGoodsListAdornResp();
            BeanUtils.copyProperties(a, resp);
            return resp;
        }).collect(Collectors.toList());

        //根据商品ID获取活动商品
        List<ActivityGoodsDO> activityGoodsDOList = goodsRepository.findAllByProductIdIn(
                goodsList.stream().map(ChannelCommoditySearchResponse::getId).collect(Collectors.toList())
        );

        //组装商品所拥有的平台活动和商家活动
        if (CollectionUtil.isNotEmpty(activityGoodsDOList)) {
            //从活动商品里筛选出平台活动的活动商品
            List<ActivityGoodsDO> pfActivityGoodsList = activityGoodsDOList.stream().filter(a ->
                    a.getBelongType().equals(BelongTypeEnum.PLATFORM.getCode())
            ).collect(Collectors.toList());
            //从活动商品里筛选出商家活动的活动商品
            List<ActivityGoodsDO> mcActivityGoodsList = activityGoodsDOList.stream().filter(a ->
                    a.getBelongType().equals(BelongTypeEnum.MERCHANT.getCode())
            ).collect(Collectors.toList());

            //根据活动商品查出活动进行的平台活动
            List<PlatformActivityDO> pfActivityList = platformActivityRepository.findAllByIdInAndOuterStatus(
                    pfActivityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toList()),
                    PlatformActivityOuterStatusEnum.ONGOING.getCode()
            );
            //根据活动商品查出活动进行的商家活动
            List<MerchantActivityDO> mcActivityList = merchantActivityRepository.findAllByIdInAndInnerStatus(
                    mcActivityGoodsList.stream().map(ActivityGoodsDO::getActivityId).collect(Collectors.toList()),
                    MerchantActivityInnerStatusEnum.ONGOING.getCode()
            );

            //根据商品ID分组，获取每个商品所关联的平台活动ID
            Map<Long, List<Long>> pfActivityMap = pfActivityGoodsList.stream().collect(Collectors.groupingBy(
                    ActivityGoodsDO::getProductId, Collectors.mapping(ActivityGoodsDO::getActivityId, Collectors.toList())
            ));

            //根据商品ID分组，获取每个商品所关联的商家活动ID
            Map<Long, List<Long>> mcActivityMap = mcActivityGoodsList.stream().collect(Collectors.groupingBy(
                    ActivityGoodsDO::getProductId, Collectors.mapping(ActivityGoodsDO::getActivityId, Collectors.toList())
            ));

            //组装
            respList.forEach(resp -> {
                //封装商品所关联的平台活动
                if (CollectionUtil.isNotEmpty(pfActivityMap)) {
                    List<Map<String, Object>> activityList = pfActivityList.stream().filter(a ->
                            CollectionUtil.isNotEmpty(pfActivityMap.get(resp.getId()))
                                    && pfActivityMap.get(resp.getId()).contains(a.getId())
                    ).map(pfActivity -> {
                        Map<String, Object> m = new HashMap<>();
                        m.put("id", pfActivity.getId());
                        m.put("type", ActivityTypeEnum.getMessage(pfActivity.getActivityType()));
                        m.put("name", pfActivity.getActivityName());
                        m.put("belongType", BelongTypeEnum.PLATFORM.getCode());
                        return m;
                    }).collect(Collectors.toList());
                    resp.setActivityList(activityList);
                }

                //封装商品所关联的商家活动
                if (CollectionUtil.isNotEmpty(mcActivityMap)) {
                    List<Map<String, Object>> activityList = mcActivityList.stream().filter(a ->
                            CollectionUtil.isNotEmpty(mcActivityMap.get(resp.getId()))
                                    && mcActivityMap.get(resp.getId()).contains(a.getId())
                    ).map(mcActivity -> {
                        Map<String, Object> m = new HashMap<>();
                        m.put("id", mcActivity.getId());
                        m.put("type", ActivityTypeEnum.getMessage(mcActivity.getActivityType()));
                        m.put("name", mcActivity.getActivityName());
                        m.put("belongType", BelongTypeEnum.MERCHANT.getCode());
                        return m;
                    }).collect(Collectors.toList());
                    resp.getActivityList().addAll(activityList);
                }
            });
        }

        //如果包含ID参数不为空则按商品ID排下序
        if (CollectionUtil.isNotEmpty(req.getIdInList())) {
            respList = respList.stream().sorted(Comparator.comparingInt(a -> req.getIdInList().indexOf(a.getId()))).collect(toList());
        }

        return Wrapper.success(new PageData<>(wrapper.getData().getTotalCount(), respList));
    }

    // ===============================抽取的方法start===============================

    // 基于原代码抽取了一下, 服了, 同样的返回字段, 每个方法都返回一个, 还是内部类嵌套内部类, new个对象写的鬼屎这么长

    private Map<Long, List<Map<String, Object>>> getActivityGoodsGiveCouponMap(List<Long> activityGoodsIds) {
        Map<Long, List<ActivityGoodsCouponGroupBO>> goodsCouponListMap = goodsHandleComponent.getActivityGoodsCouponListMap(activityGoodsIds);
        return Optional.ofNullable(goodsCouponListMap)
                .map(listMap -> listMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(BeanUtil::beanToMap).collect(toList()), (e1, e2) -> e2)))
                .orElse(new HashMap<>());
    }

    private Map<Long, List<PfActivityListAdornResp.PfActivityGoodsResp.PfActivityGoodsSubsidiaryGroupResp>> getPfActivityGoodsSubsidiaryMap(List<Long> activityGoodsIds) {
        Map<Long, List<ActivityGoodsSubsidiaryGroupBO>> subsidiaryMap = goodsHandleComponent.getActivityGoodsSubsidiaryListMap(activityGoodsIds);
        return Optional.ofNullable(subsidiaryMap)
                .map(listMap -> listMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(bo -> {
                    PfActivityListAdornResp.PfActivityGoodsResp.PfActivityGoodsSubsidiaryGroupResp activityGoodsSubsidiaryGroupResp = new PfActivityListAdornResp.PfActivityGoodsResp.PfActivityGoodsSubsidiaryGroupResp();
                    activityGoodsSubsidiaryGroupResp.setGroupNo(bo.getGroupNo());
                    activityGoodsSubsidiaryGroupResp.setLimitValue(bo.getLimitValue());
                    activityGoodsSubsidiaryGroupResp.setGroupPrice(bo.getGroupPrice());

                    List<PfActivityListAdornResp.PfActivityGoodsResp.PfActivityGoodsSubsidiaryGroupResp.PfActivityGoodsSubsidiaryGroupDetailsResp> detailList = bo.getList().stream().map(detail -> {
                        PfActivityListAdornResp.PfActivityGoodsResp.PfActivityGoodsSubsidiaryGroupResp.PfActivityGoodsSubsidiaryGroupDetailsResp activityGoodsSubsidiaryGroupDetailsResp = new PfActivityListAdornResp.PfActivityGoodsResp.PfActivityGoodsSubsidiaryGroupResp.PfActivityGoodsSubsidiaryGroupDetailsResp();
                        activityGoodsSubsidiaryGroupDetailsResp.setId(detail.getId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductId(detail.getProductId());
                        activityGoodsSubsidiaryGroupDetailsResp.setSkuId(detail.getSkuId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductName(detail.getProductName());
                        activityGoodsSubsidiaryGroupDetailsResp.setCategory(detail.getCategory());
                        activityGoodsSubsidiaryGroupDetailsResp.setBrand(detail.getBrand());
                        activityGoodsSubsidiaryGroupDetailsResp.setUnit(detail.getUnit());
                        activityGoodsSubsidiaryGroupDetailsResp.setPrice(detail.getPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setSwapPrice(detail.getSwapPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setNum(detail.getNum());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductImgUrl(detail.getProductImgUrl());
                        return activityGoodsSubsidiaryGroupDetailsResp;
                    }).collect(toList());

                    activityGoodsSubsidiaryGroupResp.setGoodsSubsidiaryGroupDetailsList(detailList);

                    return activityGoodsSubsidiaryGroupResp;

                }).collect(toList()), (e1, e2) -> e2)))
                .orElse(new HashMap<>());
    }

    private Map<Long, List<McActivityListAdornResp.McActivityGoodsResp.McActivityGoodsSubsidiaryGroupResp>> getMcActivityGoodsSubsidiaryMap(List<Long> activityGoodsIds) {
        Map<Long, List<ActivityGoodsSubsidiaryGroupBO>> subsidiaryMap = goodsHandleComponent.getActivityGoodsSubsidiaryListMap(activityGoodsIds);
        return Optional.ofNullable(subsidiaryMap)
                .map(listMap -> listMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(bo -> {
                    McActivityListAdornResp.McActivityGoodsResp.McActivityGoodsSubsidiaryGroupResp activityGoodsSubsidiaryGroupResp = new McActivityListAdornResp.McActivityGoodsResp.McActivityGoodsSubsidiaryGroupResp();
                    activityGoodsSubsidiaryGroupResp.setGroupNo(bo.getGroupNo());
                    activityGoodsSubsidiaryGroupResp.setLimitValue(bo.getLimitValue());
                    activityGoodsSubsidiaryGroupResp.setGroupPrice(bo.getGroupPrice());

                    List<McActivityListAdornResp.McActivityGoodsResp.McActivityGoodsSubsidiaryGroupResp.McActivityGoodsSubsidiaryGroupDetailsResp> detailList = bo.getList().stream().map(detail -> {
                        McActivityListAdornResp.McActivityGoodsResp.McActivityGoodsSubsidiaryGroupResp.McActivityGoodsSubsidiaryGroupDetailsResp activityGoodsSubsidiaryGroupDetailsResp = new McActivityListAdornResp.McActivityGoodsResp.McActivityGoodsSubsidiaryGroupResp.McActivityGoodsSubsidiaryGroupDetailsResp();
                        activityGoodsSubsidiaryGroupDetailsResp.setId(detail.getId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductId(detail.getProductId());
                        activityGoodsSubsidiaryGroupDetailsResp.setSkuId(detail.getSkuId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductName(detail.getProductName());
                        activityGoodsSubsidiaryGroupDetailsResp.setCategory(detail.getCategory());
                        activityGoodsSubsidiaryGroupDetailsResp.setBrand(detail.getBrand());
                        activityGoodsSubsidiaryGroupDetailsResp.setUnit(detail.getUnit());
                        activityGoodsSubsidiaryGroupDetailsResp.setPrice(detail.getPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setSwapPrice(detail.getSwapPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setNum(detail.getNum());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductImgUrl(detail.getProductImgUrl());
                        return activityGoodsSubsidiaryGroupDetailsResp;
                    }).collect(toList());

                    activityGoodsSubsidiaryGroupResp.setGoodsSubsidiaryGroupDetailsList(detailList);

                    return activityGoodsSubsidiaryGroupResp;

                }).collect(toList()), (e1, e2) -> e2)))
                .orElse(new HashMap<>());
    }

    private Map<Long, List<ActivityGoodsAdornResp.ActivityGoodsSubsidiaryGroupResp>> getActivityGoodsSubsidiaryMap(List<Long> activityGoodsIds) {
        Map<Long, List<ActivityGoodsSubsidiaryGroupBO>> subsidiaryMap = goodsHandleComponent.getActivityGoodsSubsidiaryListMap(activityGoodsIds);
        return Optional.ofNullable(subsidiaryMap)
                .map(listMap -> listMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(bo -> {
                    ActivityGoodsAdornResp.ActivityGoodsSubsidiaryGroupResp activityGoodsSubsidiaryGroupResp = new ActivityGoodsAdornResp.ActivityGoodsSubsidiaryGroupResp();
                    activityGoodsSubsidiaryGroupResp.setGroupNo(bo.getGroupNo());
                    activityGoodsSubsidiaryGroupResp.setLimitValue(bo.getLimitValue());
                    activityGoodsSubsidiaryGroupResp.setGroupPrice(bo.getGroupPrice());

                    List<ActivityGoodsAdornResp.ActivityGoodsSubsidiaryGroupResp.ActivityGoodsSubsidiaryGroupDetailsResp> detailList = bo.getList().stream().map(detail -> {
                        ActivityGoodsAdornResp.ActivityGoodsSubsidiaryGroupResp.ActivityGoodsSubsidiaryGroupDetailsResp activityGoodsSubsidiaryGroupDetailsResp = new ActivityGoodsAdornResp.ActivityGoodsSubsidiaryGroupResp.ActivityGoodsSubsidiaryGroupDetailsResp();
                        activityGoodsSubsidiaryGroupDetailsResp.setId(detail.getId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductId(detail.getProductId());
                        activityGoodsSubsidiaryGroupDetailsResp.setSkuId(detail.getSkuId());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductName(detail.getProductName());
                        activityGoodsSubsidiaryGroupDetailsResp.setCategory(detail.getCategory());
                        activityGoodsSubsidiaryGroupDetailsResp.setBrand(detail.getBrand());
                        activityGoodsSubsidiaryGroupDetailsResp.setUnit(detail.getUnit());
                        activityGoodsSubsidiaryGroupDetailsResp.setPrice(detail.getPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setSwapPrice(detail.getSwapPrice());
                        activityGoodsSubsidiaryGroupDetailsResp.setNum(detail.getNum());
                        activityGoodsSubsidiaryGroupDetailsResp.setProductImgUrl(detail.getProductImgUrl());
                        return activityGoodsSubsidiaryGroupDetailsResp;
                    }).collect(toList());

                    activityGoodsSubsidiaryGroupResp.setGoodsSubsidiaryGroupDetailsList(detailList);

                    return activityGoodsSubsidiaryGroupResp;

                }).collect(toList()), (e1, e2) -> e2)))
                .orElse(new HashMap<>());
    }

    // ===============================抽取的方法end===============================
}
